<?php

/**
 * payment actions.
 *
 * @package    erp-crm
 * @subpackage payment
 * @author     Milwell H. Sia
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class paymentActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request){}
  
  public function executeCreateCash(sfWebRequest $request)
  {
    $this->initializeCreate($request);
    $this->transaction_type='CASH';
    $this->setTemplate('create');
    $this->setLayout(false);
  }

  public function executeCreateCheck(sfWebRequest $request)
  {
    $this->initializeCreate($request);
    $this->transaction_type='CHECK';
    $this->setTemplate('create');
    $this->setLayout(false);
  }

  public function initializeCreate(sfWebRequest $request)
  {
    $this->accountCustomer = AccountCustomerPeer::retrieveByPk($request->getParameter('contact_iden'));
    $this->forward404Unless($this->accountCustomer);
    $this->total_receivable = $this->accountCustomer->getTotalReceivable();
    $this->documentForm = new DocumentForm();
    $this->paymentForm = new PaymentForm();
    $this->paymentInvoiceForm = new PaymentInvoiceForm();
    $this->paymentChecksForm = new PaymentChecksForm();
    $this->documentForm->setDefault('owner_iden',$this->accountCustomer->getDefaultOwnerIden());
    $this->paymentForm->setDefault('customer_iden',$this->accountCustomer->getContactIden());
    $this->contact = $this->accountCustomer->getContact();
    if(sfConfig::get('mod_payment_number_auto'))
      $this->paymentForm->setNumberReadOnly();
    $this->error_message='';
  }

  public function executeInsert(sfWebRequest $request){
    $document_iden = myStringGenerator::getIden();
    $check_iden = myStringGenerator::getIden();
    $document_params = $request->getParameter('document');
    $payment_params = $request->getParameter('payment');
    $payment_checks_params = $request->getParameter('payment_checks');
    
    $this->transaction_type = $payment_params['transaction_type'];
    $this->accountCustomer = AccountCustomerPeer::retrieveByPk($payment_params['customer_iden']);
    $this->forward404Unless($this->accountCustomer);
    $this->total_receivable = $this->accountCustomer->getTotalReceivable();
    $this->contact = $this->accountCustomer->getContact();
    
    $this->documentForm = new DocumentForm();
    $this->paymentForm = new PaymentForm();
    $this->paymentInvoiceForm = new PaymentInvoiceForm();
    $this->paymentChecksForm = new PaymentChecksForm();
    
    $document_params['document_type'] = 'PAYMENT';
    $document_params['void'] = 'N';
    $document_params['void_date'] = null;
    $document_params['document_iden']=$document_iden;
    $payment_params['payment_iden']=$document_iden;
    
    if((sfConfig::get('mod_payment_number_auto'))&&(! $payment_params['payment_number'])){
      $payment_number = ListDocumentTypesPeer::getNextId('PAYMENT',$payment_params['payment_type']);
      if ($payment_number){
        $payment_params['payment_number'] = vsprintf(sfConfig::get('mod_payment_number_format'),$payment_number);
        $this->paymentForm->setNumberTypeReadOnly();
      }
    }
    
    if($payment_params['transaction_type']=='CHECK'){
      $payment_params['cash'] = 0;
      $this->paymentForm->setCashMinAllowZero();
    }
    $this->documentForm->bind($document_params);
    $this->paymentForm->bind($payment_params);
    $this->error_message = '';
    if($payment_params['transaction_type']=='CASH'){
      if((sfConfig::get('mod_payment_number_strict'))&&($this->isUnique($payment_params['payment_iden'],$payment_params['payment_type'],$payment_params['payment_number'])>0)){
        $this->error_message = $payment_params['payment_type'].'-'.$payment_params['payment_number'].' already exists.';
        return $this->setTemplate('create');
      }
      if(! ($this->documentForm->isValid() && 
            $this->paymentForm->isValid()))
        return $this->setTemplate('create');
    }else{
      $payment_checks_params['payment_iden'] = $document_iden;
      $payment_checks_params['check_iden'] = $check_iden;
      $payment_checks_invoice_params['check_iden'] = $check_iden;
      $payment_checks_params['check_amount'] = $payment_checks_params['check_amount']?$payment_checks_params['check_amount']:0;
      $this->paymentChecksForm->bind($payment_checks_params);
      if((sfConfig::get('mod_payment_number_strict'))&&($this->isUnique($payment_params['payment_iden'],$payment_params['payment_type'],$payment_params['payment_number'])>0)){
        $this->error_message = $payment_params['payment_type'].'-'.$payment_params['payment_number'].' already exists.';
        return $this->setTemplate('create');
      }
      if(! ($this->documentForm->isValid() && 
            $this->paymentForm->isValid() && 
            $this->paymentChecksForm->isValid()))
        return $this->setTemplate('create');
    }
    $con = Propel::getConnection(LogTransactionPeer::DATABASE_NAME,Propel::CONNECTION_WRITE);
    $con->beginTransaction();
    try{   
      $this->documentForm->save();
      $this->paymentForm->save();
      if($this->paymentForm->getObject()->getCash()>0){
        $log_transaction = new LogTransaction();
        $log_transaction->setTransactionType('PAYMENT');
        $log_transaction->setIden1($this->paymentForm->getObject()->getCustomerIden());
        $log_transaction->setType1('CLIENT');
        $log_transaction->setIden2($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->setType2('PAYMENT');
        $log_transaction->setIden3($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->setType3('CASH');
        $log_transaction->setDebit($this->paymentForm->getObject()->getCash());
        $log_transaction->setDocumentIden($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->save();
      }
      if($this->paymentChecksForm->getValue('check_amount')>0)
      {
        $this->paymentChecksForm->save();
        $log_transaction = new LogTransaction();
        $log_transaction->setTransactionType('PAYMENT');
        $log_transaction->setIden1($this->paymentForm->getObject()->getCustomerIden());
        $log_transaction->setType1('CLIENT');
        $log_transaction->setIden2($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->setType2('PAYMENT');
        $log_transaction->setIden3($this->paymentChecksForm->getObject()->getCheckIden());
        $log_transaction->setType3('CHECK');
        $log_transaction->setDebit($this->paymentChecksForm->getObject()->getCheckAmount());
        $log_transaction->setDocumentIden($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->save();
      }
      $con->commit();
      $this->redirect('payment/edit?payment_iden='.$this->paymentForm->getObject()->getPaymentIden());
    }catch(Exception $e){
      $con->rollBack();
      $request->getParameterHolder()->set('message','P'.$e->getMessage().'Y');
      $this->forward('main','error');
    }
    
  }
  
  public function executeEdit(sfWebRequest $request){
    $payment_iden = $request->getParameter('payment_iden');
    $document = DocumentPeer::retrieveByPk($payment_iden);
    $payment = PaymentPeer::retrieveByPk($payment_iden);
    $this->forward404Unless(($payment && $document));
    $this->documentForm = new DocumentForm($document);
    $this->paymentForm = new PaymentForm($payment);
    $this->paymentInvoices = $payment->getPaymentInvoices();
    $this->paymentCheckss = $payment->getPaymentCheckss();
    $this->transaction_type = $this->paymentForm->getObject()->getTransactionType();
    $this->error_message = '';
    if(sfConfig::get('mod_payment_number_auto'))
      $this->paymentForm->setNumberTypeReadOnly();
    $this->setLayout(false);
  }
  
  public function executeUpdate(sfWebRequest $request){
    $document_params = $request->getParameter('document');
    $document_params['document_type'] = 'PAYMENT';
    $document_params['void'] = 'N';
    $document_params['void_date'] = null;
    $payment_params = $request->getParameter('payment');
    $payment_iden = $payment_params['payment_iden'];
    $document = DocumentPeer::retrieveByPk($payment_iden);
    $payment = PaymentPeer::retrieveByPk($payment_iden);
    $this->forward404Unless(($payment && $document));
    $cash = $payment->getCash();
    $this->documentForm = new DocumentForm($document);
    $this->paymentForm = new PaymentForm($payment);
    if ($payment->getTransactionType()=='CHECK'){
      $payment_params['cash'] = 0;
      $this->paymentForm->setCashMinAllowZero();
    }
    $this->documentForm->bind($document_params);
    $this->paymentForm->bind($payment_params);
    if((sfConfig::get('mod_payment_number_strict'))&&($this->isUnique($payment_params['payment_iden'],$payment_params['payment_type'],$payment_params['payment_number'])>0)){
      $this->transaction_type = $payment->getTransactionType();
      $this->paymentInvoices = $payment->getPaymentInvoices();
      $this->paymentCheckss = $payment->getPaymentCheckss();
      $this->setLayout(false);
      $this->error_message = $payment_params['payment_type'].'-'.$payment_params['payment_number'].' already exists.';
      return $this->setTemplate('edit');
    }
    if(! ($this->documentForm->isValid() && 
          $this->paymentForm->isValid())){
      $this->transaction_type = $payment->getTransactionType();
      $this->paymentInvoices = $payment->getPaymentInvoices();
      $this->paymentCheckss = $payment->getPaymentCheckss();
      $this->setLayout(false);
      return $this->setTemplate('edit');
    }
      $con = Propel::getConnection(LogTransactionPeer::DATABASE_NAME,Propel::CONNECTION_WRITE);
      $con->beginTransaction();
      try{
        $this->documentForm->save();
        $this->paymentForm->save();
        $log_transaction = new LogTransaction();
        $log_transaction->setTransactionType('PAYMENT');
        $log_transaction->setIden1($this->paymentForm->getObject()->getCustomerIden());
        $log_transaction->setType1('CLIENT');
        $log_transaction->setIden2($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->setType2('PAYMENT');
        $log_transaction->setIden3($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->setType3('CASH');
        $log_transaction->setCredit($cash);
        $log_transaction->setDocumentIden($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->save();
        $log_transaction = new LogTransaction();
        $log_transaction->setTransactionType('PAYMENT');
        $log_transaction->setIden1($this->paymentForm->getObject()->getCustomerIden());
        $log_transaction->setType1('CLIENT');
        $log_transaction->setIden2($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->setType2('PAYMENT');
        $log_transaction->setIden3($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->setType3('CASH');
        $log_transaction->setDebit($this->paymentForm->getObject()->getCash());
        $log_transaction->setDocumentIden($this->paymentForm->getObject()->getPaymentIden());
        $log_transaction->save();
        $con->commit();
        $this->redirect('payment/edit?payment_iden='.$payment->getPaymentIden());
      }catch(Exception $e){
        $con->rollBack();
        $request->getParameterHolder()->set('message','P'.$e->getMessage().'Y');
        $this->forward('main','error');
      }
    
    
  }
  
  public function executeSearch(sfWebRequest $request)
  {
    $this->paymentSearchForm = new myPaymentSearchForm();
  }
  
  public function executeDoSearch(sfWebRequest $request){
    $search_keys = $request->getParameter('skey_payment');
    $paymentSearchForm = new myPaymentSearchForm();
    $paymentSearchForm->bind($search_keys);
    
    $c = new Criteria();
    if($paymentSearchForm['payment_type']->getValue())
      $c->addAnd(PaymentPeer::PAYMENT_TYPE,$paymentSearchForm['payment_type']->getValue());
    if($paymentSearchForm['payment_number_from']->getValue())
      $c->addAnd(PaymentPeer::PAYMENT_NUMBER,$paymentSearchForm['payment_number_from']->getValue(),Criteria::GREATER_EQUAL);
    if($paymentSearchForm['payment_number_to']->getValue())
      $c->addAnd(PaymentPeer::PAYMENT_NUMBER,$paymentSearchForm['payment_number_to']->getValue(),Criteria::LESS_EQUAL);
    $payment_date_from = $paymentSearchForm['payment_date_from']->getValue();
    $payment_date_from_str = $payment_date_from['year'].'-'.$payment_date_from['month'].'-'.$payment_date_from['day'];
    if($payment_date_from_str != '--')
      $c->addAnd(DocumentPeer::DOCUMENT_DATE,$payment_date_from_str,Criteria::GREATER_EQUAL);
    $payment_date_to = $paymentSearchForm['payment_date_to']->getValue();
    $payment_date_to_str = $payment_date_to['year'].'-'.$payment_date_to['month'].'-'.$payment_date_to['day'];
    if($payment_date_to_str != '--')
      $c->addAnd(DocumentPeer::DOCUMENT_DATE,$payment_date_to_str,Criteria::LESS_EQUAL);
    if($paymentSearchForm['customer_name']->getValue())
      $c->addAnd(ContactPeer::LIST_NAME,'%'.$paymentSearchForm['customer_name']->getValue().'%',Criteria::LIKE);
    if($paymentSearchForm['show_void_only']->getValue()!='Y')
      $c->addAnd(DocumentPeer::VOID,'N');
    else
      $c->addAnd(DocumentPeer::VOID,'Y');
    if($paymentSearchForm['invoice_type']->getValue()){
      $c->addJoin(PaymentInvoicePeer::PAYMENT_IDEN,PaymentPeer::PAYMENT_IDEN);
      $c->addJoin(PaymentInvoicePeer::INVOICE_IDEN,InvoicePeer::INVOICE_IDEN);
      $c->addAnd(InvoicePeer::INVOICE_TYPE,$paymentSearchForm['invoice_type']->getValue());
      if($paymentSearchForm['invoice_id_from']->getValue())
        $c->addAnd(InvoicePeer::INVOICE_ID,$paymentSearchForm['invoice_id_from']->getValue(),Criteria::GREATER_EQUAL);
      if($paymentSearchForm['invoice_id_to']->getValue())
        $c->addAnd(InvoicePeer::INVOICE_ID,$paymentSearchForm['invoice_id_to']->getValue(),Criteria::LESS_EQUAL);
    }
    
    $c->addJoin(PaymentPeer::PAYMENT_IDEN,DocumentPeer::DOCUMENT_IDEN);
    $c->addJoin(PaymentPeer::CUSTOMER_IDEN,ContactPeer::IDEN);
    $this->payments = PaymentPeer::doSelect($c);
    
  }
  
  public function executeAddInvoice(sfWebRequest $request){
    $this->payment_iden = $request->getParameter('payment_iden');
    $this->customer_iden = $request->getParameter('customer_iden');
    $this->payment = PaymentPeer::retrieveByPk($this->payment_iden);
    $this->owner_iden = $this->payment->getDocument()->getOwnerIden();
    $this->paymentInvoiceForm = new PaymentInvoiceForm();
    $this->paymentInvoiceForm->setDefault('payment_iden',$this->payment_iden);
    $this->setLayout(false);
  }
  
  public function executeInsertInvoice(sfWebRequest $request){
    $payment_invoice_params = $request->getParameter('payment_invoice');
    $this->payment = PaymentPeer::retrieveByPk($payment_invoice_params['payment_iden']);
    $this->forward404Unless($this->payment);
    $this->payment_iden = $this->payment->getPaymentIden();
    $this->customer_iden = $this->payment->getCustomerIden();
    $this->paymentInvoiceForm = new PaymentInvoiceForm();
    $payment_invoice_params['amount'] = $payment_invoice_params['amount']?$payment_invoice_params['amount']:0;
    $this->paymentInvoiceForm->bind($payment_invoice_params);
    if(! $this->paymentInvoiceForm->isValid())
      return $this->setTemplate('addInvoice');
    $c = new Criteria();
    $c->add(PaymentInvoicePeer::PAYMENT_IDEN,$payment_invoice_params['payment_iden']);
    $c->add(PaymentInvoicePeer::INVOICE_IDEN,$payment_invoice_params['invoice_iden']);
    $paymentInvoice = PaymentInvoicePeer::doSelectOne($c);
    if($paymentInvoice){
      $message = 'Invoice '.$paymentInvoice->getInvoice()->getInvoiceNumber().' is already entered.';
      return $this->redirect('payment/showInvoices?payment_iden='.$this->payment_iden.'&message='.$message);
    }else{
      if ($payment_invoice_params['amount']<0){
        $message = 'Amount cannot be negative';
        return $this->redirect('payment/showInvoices?payment_iden='.$this->payment_iden.'&message='.$message);
      }elseif ($this->payment->getTotalPayment() < ($this->payment->getInvoiceTotal()+$payment_invoice_params['amount'])){
        $message = 'Total payment is only '.number_format($this->payment->getTotalPayment(),2);
        return $this->redirect('payment/showInvoices?payment_iden='.$this->payment_iden.'&message='.$message);
      }else
        $con = Propel::getConnection();
        $invoice_balance = myQuery::getInvoiceBalance($con,$payment_invoice_params['invoice_iden']);
        if($payment_invoice_params['amount'] > $invoice_balance['total']){
          $message = 'Invoice '.$invoice_balance['invoice_id'].', balance is only '.number_format($invoice_balance['total'],2);
          return $this->redirect('payment/showInvoices?payment_iden='.$this->payment_iden.'&message='.$message);
        }
    }
    $con = Propel::getConnection(LogTransactionPeer::DATABASE_NAME,Propel::CONNECTION_WRITE);
    $con->beginTransaction();
    try{
      $this->paymentInvoiceForm->save();
      $log_transaction = new LogTransaction();
      $log_transaction->setTransactionType('PAYMENT');
      $log_transaction->setIden1($this->payment->getCustomerIden());
      $log_transaction->setType1('CLIENT');
      $log_transaction->setIden2($this->payment->getPaymentIden());
      $log_transaction->setType2('PAYMENT');
      $log_transaction->setIden3($this->payment->getPaymentIden());
      $log_transaction->setType3($this->payment->getPaymentType());
      $log_transaction->setIden4($this->paymentInvoiceForm->getObject()->getInvoiceIden());
      $log_transaction->setType4('INVOICE');
      $log_transaction->setCredit($this->paymentInvoiceForm->getObject()->getAmount());
      $log_transaction->setDocumentIden($this->payment->getPaymentIden());
      $log_transaction->save();
      $log_transaction = new LogTransaction();
      $log_transaction->setTransactionType('INVOICE');
      $log_transaction->setIden1($this->payment->getCustomerIden());
      $log_transaction->setType1('CLIENT');
      $log_transaction->setIden2($this->paymentInvoiceForm->getObject()->getInvoiceIden());
      $log_transaction->setType2('INVOICE');
      $log_transaction->setIden3($this->payment->getPaymentIden());
      $log_transaction->setType3('PAYMENT');
      $log_transaction->setIden3($this->payment->getPaymentIden());
      $log_transaction->setType3($this->payment->getPaymentType());
      $log_transaction->setCredit($this->paymentInvoiceForm->getObject()->getAmount());
      $log_transaction->setDocumentIden($this->payment->getPaymentIden());
      $log_transaction->save();
      $con->commit();
      $this->redirect('payment/showInvoices?payment_iden='.$this->payment_iden);
    }catch(Exception $e){
      $con->rollBack();
      $request->getParameterHolder()->set('message','P'.$e->getMessage().'Y');
      $this->forward('main','error');
    }
  }
  
  public function executeDeleteInvoice(sfWebRequest $request){
    $payment_iden = $request->getParameter('payment_iden');
    $invoice_iden = $request->getParameter('invoice_iden');
    $c = new Criteria();
    $c->Add(PaymentInvoicePeer::PAYMENT_IDEN,$payment_iden);
    $c->Add(PaymentInvoicePeer::INVOICE_IDEN,$invoice_iden);
    $paymentInvoice = PaymentInvoicePeer::doSelectOne($c);
    $payment = $paymentInvoice->getPayment();
    $con = Propel::getConnection(LogTransactionPeer::DATABASE_NAME,Propel::CONNECTION_WRITE);
    $con->beginTransaction();
    try{
      $log_transaction = new LogTransaction();
      $log_transaction->setTransactionType('PAYMENT');
      $log_transaction->setIden1($payment->getCustomerIden());
      $log_transaction->setType1('CLIENT');
      $log_transaction->setIden2($payment->getPaymentIden());
      $log_transaction->setType2('PAYMENT');
      $log_transaction->setIden3($payment->getPaymentIden());
      $log_transaction->setType3($payment->getPaymentType());
      $log_transaction->setIden4($paymentInvoice->getInvoiceIden());
      $log_transaction->setType4('INVOICE');
      $log_transaction->setDebit($paymentInvoice->getAmount());
      $log_transaction->setDocumentIden($payment->getPaymentIden());
      $log_transaction->save();
      $log_transaction = new LogTransaction();
      $log_transaction->setTransactionType('INVOICE');
      $log_transaction->setIden1($payment->getCustomerIden());
      $log_transaction->setType1('CLIENT');
      $log_transaction->setIden2($paymentInvoice->getInvoiceIden());
      $log_transaction->setType2('INVOICE');
      $log_transaction->setIden3($payment->getPaymentIden());
      $log_transaction->setType3($payment->getPaymentType());
      $log_transaction->setDebit($paymentInvoice->getAmount());
      $log_transaction->setDocumentIden($payment->getPaymentIden());
      $log_transaction->save();
      $paymentInvoice->delete();
      $con->commit();
      return $this->renderText(json_encode(array('payment_iden'=>$payment_iden,)));
    }catch(Exception $e){
      $con->rollBack();
      $request->getParameterHolder()->set('message','P'.$e->getMessage().'Y');
      $this->forward('main','error');
    }
    
  }
  
  public function executeShowInvoices(sfWebRequest $request){
    $payment_iden = $request->getParameter('payment_iden');
    $payment = PaymentPeer::retrieveByPk($payment_iden);
    $customer_iden = $payment->getCustomerIden();
    $paymentInvoices = $payment->getPaymentInvoices();
    return $this->renderPartial(
            'payment_invoice_grid',
            array(
              'paymentInvoices'=>$paymentInvoices,
              'payment_iden'=>$payment_iden,
              'customer_iden'=>$customer_iden,
              'total_payment'=>$payment->getTotalPayment(),
              'message'=>$request->getParameter('message',''),
              'void'=>'N',
            )
          );
    
  }
  
  public function executeAddCheck(sfWebRequest $request){
    $this->payment_iden = $request->getParameter('payment_iden');
    $this->paymentChecksForm = new PaymentChecksForm();
    $this->paymentChecksForm->setDefault('payment_iden',$this->payment_iden);
    $this->setLayout(false);
  }
  
  public function executeInsertCheck(sfWebRequest $request){
    $payment_checks_params = $request->getParameter('payment_checks');
    $payment_checks_params['check_iden'] = myStringGenerator::getIden();
    $this->payment = PaymentPeer::retrieveByPk($payment_checks_params['payment_iden']);
    $this->forward404Unless($this->payment);
    $this->payment_iden = $this->payment->getPaymentIden();
    $this->contact = $this->payment->getAccountCustomer()->getContact();
    $this->paymentChecksForm = new PaymentChecksForm();
    $payment_checks_params['check_amount'] = $payment_checks_params['check_amount']?$payment_checks_params['check_amount']:0;
    $this->paymentChecksForm->bind($payment_checks_params);
    if(! $this->paymentChecksForm->isValid())
      return $this->setTemplate('addCheck');
    $con = Propel::getConnection(LogTransactionPeer::DATABASE_NAME,Propel::CONNECTION_WRITE);
    $con->beginTransaction();
    try{
      $this->paymentChecksForm->save();
      $log_transaction = new LogTransaction();
      $log_transaction->setTransactionType('PAYMENT');
      $log_transaction->setIden1($this->payment->getCustomerIden());
      $log_transaction->setType1('CLIENT');
      $log_transaction->setIden2($this->payment->getPaymentIden());
      $log_transaction->setType2('PAYMENT');
      $log_transaction->setIden3($this->paymentChecksForm->getObject()->getCheckIden());
      $log_transaction->setType3('CHECK');
      $log_transaction->setDebit($this->paymentChecksForm->getObject()->getCheckAmount());
      $log_transaction->setDocumentIden($this->payment->getPaymentIden());
      $log_transaction->save();
      $con->commit();
      $this->redirect('payment/showChecks?payment_iden='.$this->payment->getPaymentIden());
    }catch(Exception $e){
      $con->rollBack();
      $request->getParameterHolder()->set('message','P'.$e->getMessage().'Y');
      $this->forward('main','error');
    }
  }
  
  
  public function executeShowChecks(sfWebRequest $request){
    $payment_iden = $request->getParameter('payment_iden');
    $message = $request->getParameter('message');
    $c = new Criteria();
    $c->add(PaymentChecksPeer::PAYMENT_IDEN,$payment_iden);
    $paymentCheckss = PaymentChecksPeer::doSelect($c);
    
    return $this->renderPartial('payment_checks_grid',array('paymentCheckss'=>$paymentCheckss,'payment_iden'=>$payment_iden,'message'=>$message,'void'=>'N',));
    
  }
  
  public function executeVerifyCheckDelete(sfWebRequest $request){
    $payment_iden = $request->getParameter('payment_iden');
    $check_iden = $request->getParameter('check_iden');
    $payment = PaymentPeer::retrieveByPk($payment_iden);
    $paymentChecks = PaymentChecksPeer::retrieveByPk($payment_iden,$check_iden);
    $invoice_total = $payment->getInvoiceTotal();
    $payment_total = $payment->getTotalPayment() - $paymentChecks->getCheckAmount();
    if ($payment_total<$invoice_total)
      return $this->renderText(json_encode(array('success'=>false,'payment_iden'=>$request->getParameter('payment_iden'),'message'=>'Invoice total is '.number_format($invoice_total,2),)));
    return $this->renderText(json_encode(array('success'=>true,'payment_iden'=>$request->getParameter('payment_iden'),'check_iden'=>$check_iden,'message'=>'',)));
  }
  
  public function executeDeleteCheck(sfWebRequest $request){
    $payment_iden = $request->getParameter('payment_iden');
    $check_iden = $request->getParameter('check_iden');
    $c = new Criteria();
    $c->Add(PaymentChecksPeer::PAYMENT_IDEN,$payment_iden);
    $c->Add(PaymentChecksPeer::CHECK_IDEN,$check_iden);
    $paymentChecks = PaymentChecksPeer::doSelectOne($c);
    $payment = $paymentChecks->getPayment();
    $con = Propel::getConnection(LogTransactionPeer::DATABASE_NAME,Propel::CONNECTION_WRITE);
    $con->beginTransaction();
    try{
      $log_transaction = new LogTransaction();
      $log_transaction->setTransactionType('PAYMENT');
      $log_transaction->setIden1($payment->getCustomerIden());
      $log_transaction->setType1('CLIENT');
      $log_transaction->setIden2($payment->getPaymentIden());
      $log_transaction->setType2('PAYMENT');
      $log_transaction->setIden3($paymentChecks->getCheckIden());
      $log_transaction->setType3('CHECK');
      $log_transaction->setCredit($paymentChecks->getCheckAmount());
      $log_transaction->setDocumentIden($payment->getPaymentIden());
      $log_transaction->save();
      $paymentChecks->delete();
      $con->commit();
      return $this->renderText(json_encode(array('payment_iden'=>$payment_iden,)));
    }catch(Exception $e){
      $con->rollBack();
      $request->getParameterHolder()->set('message','P'.$e->getMessage().'Y');
      $this->forward('main','error');
    }
  }
  
  public function executeVoid(sfWebRequest $request){
    $payment = PaymentPeer::retrieveByPk($request->getParameter('payment_iden'));
    $this->forward404Unless($payment);
    $document = $payment->getDocument();
    $document->void();
    return $this->renderText(json_encode(array('payment_iden'=>$payment->getPaymentIden(),)));
  }
  
  public function executeGetGridTd(sfWebRequest $request){
    $payment = PaymentPeer::retrieveByPk($request->getParameter('payment_iden'));
    return $this->renderPartial('payment_grid_td',array('payment'=>$payment,));
  }

  private function isUnique($payment_iden,$payment_type,$payment_number){
    $c = new Criteria();
    if ($payment_iden)
      $c->addAnd(PaymentPeer::PAYMENT_IDEN,$payment_iden,Criteria::NOT_EQUAL);
    $c->addAnd(PaymentPeer::PAYMENT_TYPE,$payment_type);
    $c->addAnd(PaymentPeer::PAYMENT_NUMBER,$payment_number);
    $c->addJoin(DocumentPeer::DOCUMENT_IDEN,PaymentPeer::PAYMENT_IDEN);
    $c->addAnd(DocumentPeer::VOID,'N');
    return PaymentPeer::doCount($c);
  }
  
  public function executeCheckId(sfWebRequest $request){
    $payment_iden = $request->getParameter('payment_iden');
    $payment_type = $request->getParameter('payment_type');
    $payment_number = $request->getParameter('payment_number');
    $count = $this->isUnique($payment_iden,$payment_type,$payment_number);
    return $this->renderText(json_encode(array('count'=>$count,)));
  }



}
